package pdatabase

import (
	"sync"

	"gitee.com/linxing_3/sr-core/config"
	"gitee.com/linxing_3/sr-core/plugins/log"
	"gitee.com/linxing_3/sr-core/plugins/storage/database"
	"gitee.com/linxing_3/sr-core/relay"
	"gitee.com/mkwchecking/sr-admin/pkg/instance"
)

type YDatabaseKey struct{}

var dbLock = &sync.Mutex{}

func UpsertDatabase() (database.IDataSet, error) {
	dbLock.Lock()
	defer dbLock.Unlock()

	db, err := instance.GetOrInit(YDatabaseKey{}, initDatabase)
	if err != nil {
		return nil, err
	}

	return *db, nil
}

func GetDatabaseE() (database.IDataSet, error) {
	db, err := instance.GetInstance[database.IDataSet](YDatabaseKey{})
	if err != nil {
		return nil, err
	}
	return *db, nil
}

func MustGetDatabase() database.IDataSet {
	db, err := GetDatabaseE()
	if err != nil {
		panic(err)
	}
	return db
}

func initDatabase() (database.IDataSet, error) {
	if db, ok := database.FromCtx(relay.Context()); ok {
		return db, nil
	}

	return database.Install(config.Get().Database, log.GetDefault())
}
